package com.ruoyi.web.controller.tool;



import com.ruoyi.system.domain.Tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : [LiuYanQiang]
 * @version : [v1.0]
 * @className : ReplacementTree
 * @description : [树型结构装换]
 * @createTime : [2022/5/2 23:37]
 * @updateUser : [LiuYanQiang]
 * @updateTime : [2022/5/2 23:37]
 * @updateRemark : [描述说明本次修改内容]
 */
public class ReplacementTree {

    /*
     * @version V1.0
     * Title: builTree
     * @author LiuYanQiang
     * @description 始树形结构创建
     * @createTime  2022/5/3 0:18
     * @param [list]
     * @return java.util.List<com.lyq.generateTree.Tree>*/
    public List<Tree> builTree(List<Tree> list) {
        List<Tree> treeList = new ArrayList<>();
        for (Tree tree : this.getRootNode(list)) {
            //建立子树节点
            tree = this.buildChilTree(tree,list);
            //为根节点设置子树节点
            treeList.add(tree);
        }
        return treeList;
    }

    /*
     * @version V1.0
     * Title: buildChilTree
     * @author LiuYanQiang
     * @description 通过递归来创建子树形结构
     * @createTime  2022/5/3 0:18
     * @param [tree, list]
     * @return com.lyq.generateTree.Tree*/
    private Tree buildChilTree(Tree tree,List<Tree> list) {
        List<Tree> treeList = new ArrayList<>();
        for (Tree t : list) {
            //判断当前父节点是否存在子节点
            if (t.getP_id().equals(tree.getValue())) {
                treeList.add(this.buildChilTree(t,list));
            }
        }
        tree.setChildren(treeList);
        return tree;
    }

    /*
     * @version V1.0
     * Title: getRootNode
     * @author wk
     * @description 获取全部根节点
     * @createTime  2022/5/3 0:18
     * @param [list]
     * @return java.util.List<com.lyq.generateTree.Tree>*/
    private List<Tree> getRootNode(List<Tree> list) {
        List<Tree> rootList = new ArrayList<>();
        for (Tree tree : list) {
            if (tree.getP_id().equals("null")) {
                rootList.add(tree);
            }
        }
        return rootList;
    }
}
